package com.itheima.web.controller;

import com.itheima.pojo.User;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ChaunceyZhang
 * @date 2022-10-21 19:47
 * @blog1 https://zephyr-cyber.github.io/
 * @blog2 https://www.yuque.com/gougougou-xwscx
 */
@Controller
@RequestMapping("/login")
public class StudentController {
    @Autowired
    private StudentService service;

    @PostMapping
    public String login(
            HttpServletRequest request,
            @RequestParam("name") String username,
            @RequestParam("password") String password,
            HttpSession session) throws ServletException, IOException {
        // 调用用户服务对象的登录方法
        User user = service.select(username, password);
        // 判断用户是否登录成功
        if (user != null) {
            // 将登录用户名写入会话
            request.getSession().setAttribute("userName", user);

            // 删除会话里可能存在的登录错误提示信息
            if (session.getAttribute("loginMsg") != null) {
                session.removeAttribute("loginMsg");
            }
            return "redirect:/pages/list.html";
        } else {
            // 将登录错误信息写入会话
            session.setAttribute("loginMsg", "用户名或密码错误！");
            // 跳转到前台登录页面
            return "redirect:/pages/login.html";
        }
    }
}

